<template>
  <div class="f_div" v-loading="loading">
    <div class="t_div">
      基础资料 / 司机管理 / <a href="#">{{ name }}</a>
    </div>
    <el-container>
      <el-header class="header"
        ><div class="h_div">
          <div class="h_in_vid">基础信息</div>
        </div></el-header
      >
      <el-main class="main">
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          status-icon
        >
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="姓名" prop="dv_name">
                <el-input v-model="ruleForm.dv_name" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="手机号码" prop="dv_phone">
                <el-input
                  v-model="ruleForm.dv_phone"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="身份证号" prop="dv_identy">
                <el-input
                  v-model="ruleForm.dv_identy"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="性别" prop="dv_gender">
                <el-select
                  v-model="ruleForm.dv_gender"
                  placeholder="请选择"
                  :teleported="false"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.dict_code"
                    :label="item.dict_label"
                    :value="item.dict_code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="驾照类型" prop="dv_dl_type">
                <el-select
                  v-model="ruleForm.dv_dl_type"
                  placeholder="请选择"
                  :teleported="false"
                >
                  <el-option
                    v-for="item in options2"
                    :key="item.dict_code"
                    :label="item.dict_label"
                    :value="item.dict_code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="驾照有效期" prop="dv_dl_expiry">
                <el-date-picker
                  v-model="ruleForm.dv_dl_expiry"
                  type="date"
                  placeholder="请选择日期"
                  format="YYYY/MM/DD"
                  value-format="YYYY-MM-DD"
                  style="width: 400px"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="所属承运商" prop="dv_carrier">
                <el-select
                  v-model="ruleForm.dv_carrier"
                  placeholder="公司名称/承运商编码"
                  :teleported="false"
                >
                  <el-option
                    v-for="item in options3"
                    :key="item.cr_id"
                    :label="item.cr_cp_name"
                    :value="item.cr_id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="家庭住址" prop="dv_address">
                <el-input
                  v-model="ruleForm.dv_address"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="紧急联系人" prop="dv_emg_cont">
                <el-input
                  v-model="ruleForm.dv_emg_cont"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="紧急联系人电话" prop="dv_emg_ph">
                <el-input
                  v-model="ruleForm.dv_emg_ph"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="状态">
                <el-switch v-model="ruleForm.dv_drvr_st" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="证件照" prop="dv_doc_pic">
                <el-upload
                  action="http://localhost:5261/api/Company/Upload"
                  list-type="picture-card"
                  :auto-upload="true"
                  v-model:file-list="rulelist"
                  :limit="1"
                  :on-exceed="handleExceed"
                  ref="upload"
                  :on-success="handleUploadSuccess"
                  :on-error="handleUploadError"
                  class="form_content"
                >
                  <el-icon><Plus /></el-icon>

                  <template #file="{ file }">
                    <div>
                      <img
                        class="el-upload-list__item-thumbnail"
                        :src="file.url"
                        alt=""
                      />
                      <span class="el-upload-list__item-actions">
                        <span
                          class="el-upload-list__item-preview"
                          @click="handlePictureCardPreview(file)"
                        >
                          <el-icon><zoom-in /></el-icon>
                        </span>
                        <span
                          v-if="!disabled"
                          class="el-upload-list__item-delete"
                          @click="handleDownload(file)"
                        >
                          <el-icon><Download /></el-icon>
                        </span>
                        <span
                          v-if="!disabled"
                          class="el-upload-list__item-delete"
                          @click="handleRemove(file)"
                        >
                          <el-icon><Delete /></el-icon>
                        </span>
                      </span>
                    </div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="驾驶证" prop="dv_drive_lic">
                <el-upload
                  action="http://localhost:5261/api/Company/Upload"
                  list-type="picture-card"
                  :auto-upload="true"
                  v-model:file-list="rulelist2"
                  :limit="1"
                  :on-exceed="handleExceed2"
                  ref="upload2"
                  :on-success="handleUploadSuccess"
                  :on-error="handleUploadError"
                  class="form_content"
                >
                  <el-icon><Plus /></el-icon>

                  <template #file="{ file }">
                    <div>
                      <img
                        class="el-upload-list__item-thumbnail"
                        :src="file.url"
                        alt=""
                      />
                      <span class="el-upload-list__item-actions">
                        <span
                          class="el-upload-list__item-preview"
                          @click="handlePictureCardPreview(file)"
                        >
                          <el-icon><zoom-in /></el-icon>
                        </span>
                        <span
                          v-if="!disabled"
                          class="el-upload-list__item-delete"
                          @click="handleDownload(file)"
                        >
                          <el-icon><Download /></el-icon>
                        </span>
                        <span
                          v-if="!disabled"
                          class="el-upload-list__item-delete"
                          @click="handleRemove(file)"
                        >
                          <el-icon><Delete /></el-icon>
                        </span>
                      </span>
                    </div>
                  </template>
                </el-upload>
              </el-form-item>
              <el-dialog v-model="dialogVisible">
                <img
                  w-full
                  :src="dialogImageUrl"
                  alt="Preview Image"
                  style="max-width: 100%; height: auto"
                />
              </el-dialog>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="16">
              <el-form-item label="备注信息" prop="dv_cmts">
                <el-input v-model="ruleForm.dv_cmts" placeholder="请输入内容" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="16">
              <el-form-item>
                <el-button type="primary" style="width: 80px" @click="onSubmit"
                  >保存</el-button
                >
                <el-button style="width: 80px" @click="cancel">取消</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { onMounted, reactive, ref, nextTick, onUnmounted } from "vue";
import { ElMessage } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { getRandomString } from "@/randomString/random.js";
import $http from "@/axios/base";
export default {
  name: "app",
  setup() {
    let ruleForm = reactive({
      dv_id: 0,
      dv_name: "",
      dv_phone: "",
      dv_identy: "",
      dv_gender: "",
      dv_dl_type: "",
      dv_dl_expiry: "",
      dv_carrier: "",
      dv_address: "",
      dv_emg_cont: "",
      dv_emg_ph: "",
      dv_drvr_st: false,
      dv_doc_pic: "",
      dv_drive_lic: "",
      dv_cmts: "",
      create_by: sessionStorage.getItem("empname"),
      create_time: new Date().toISOString().slice(0, 10).toString(),
      is_del: 0,
      update_by: "",
      update_time: "",
    });

    let router = useRouter();
    let route = useRoute();

    let name = ref();

    let rulelist = ref([]);

    let rulelist2 = ref([]);

    let loading = ref(false);

    let options = ref([]);

    let options2 = ref([]);

    let options3 = ref([]);

    let ruleFormRef = ref(null);
    let upload = ref(null);
    let upload2 = ref(null);
    const dialogImageUrl = ref("");
    const dialogVisible = ref(false);
    const disabled = ref(false);

    const rules = reactive({
      dv_name: [
        {
          required: true,
          message: "姓名不能为空",
          trigger: "blur",
        },
      ],
      dv_phone: [
        {
          required: true,
          message: "手机号码不能为空",
          trigger: "blur",
        },
        {
          pattern:
            /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/,
          message: "请输入正确的手机号码格式",
          trigger: "blur",
        },
      ],
      dv_identy: [
        { required: true, message: "请输入身份证号码", trigger: "blur" },
        {
          pattern:
            /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
          message: "请输入正确的身份证号码",
          trigger: "blur",
        },
      ],
      dv_gender: [{ required: true, message: "请选择性别", trigger: "change" }],
      dv_dl_type: [
        { required: true, message: "请选择驾照类型", trigger: "change" },
      ],
      dv_dl_expiry: [
        { required: true, message: "请选择日期", trigger: "change" },
        { type: "date", message: "请选择正确的日期格式", trigger: "change" },
      ],
      dv_carrier: [
        { required: true, message: "请选择承运商", trigger: "change" },
      ],
      dv_doc_pic: [
        { required: true, message: "请上传证件照", trigger: "change" },
      ],
      dv_drive_lic: [
        { required: true, message: "请上传驾驶证", trigger: "change" },
      ],
    });

    function handleRemove(file) {
      const index = rulelist.value.findIndex((e) => e.name === file.name);
      if (index !== -1) {
        rulelist.value.splice(index, 1);
      }
      const index2 = rulelist2.value.findIndex((e) => e.name === file.name);
      if (index2 !== -1) {
        rulelist2.value.splice(index2, 1);
      }
    }

    function handlePictureCardPreview(file) {
      dialogImageUrl.value = file.url;
      dialogVisible.value = true;
    }

    function handleDownload(file) {
      var now = new Date();

      // 获取年、月、日、时、分、秒
      var year = now.getFullYear();
      var month = now.getMonth() + 1; // 注意月份是从 0 开始的
      var day = now.getDate();
      var imageUrl = file.url;
      var link = document.createElement("a");
      link.href = imageUrl;
      link.download =
        "七尾-" + year + month + day + getRandomString(8) + ".jpg";
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }

    function handleExceed(files) {
      // 当上传的文件数量超过限制时，清空已上传的文件列表，并上传最新的文件
      upload.value.clearFiles();
      const file = files[0]; // 获取最新的文件
      file.uid = Date.now(); // 为文件生成唯一的标识符
      upload.value.handleStart(file); // 开始上传最新的文件
      upload.value.submit();
    }

    function handleExceed2(files) {
      // 当上传的文件数量超过限制时，清空已上传的文件列表，并上传最新的文件
      upload2.value.clearFiles();
      const file = files[0]; // 获取最新的文件
      file.uid = Date.now(); // 为文件生成唯一的标识符
      upload2.value.handleStart(file); // 开始上传最新的文件
      upload2.value.submit();
    }

    const handleUploadSuccess = (response, file, fileList) => {
      // 处理上传成功的逻辑，如显示成功消息或更新UI
      console.log("上传成功", response, file, fileList);
    };

    const handleUploadError = (error, file, fileList) => {
      // 处理上传失败的逻辑，如显示错误消息或更新UI
      console.error("上传失败", error, file, fileList);
    };

    function onSubmit() {
      console.log(rulelist.value[0]);
      if (rulelist.value[0] == undefined) {
        ElMessage.warning("请上传证件照或驾驶证！！！");
        return;
      }
      if(rulelist2.value[0] == undefined)
      {
        ElMessage.warning("请上传证件照或驾驶证！！！");
        return;
      }
      if (rulelist.value[0].response != undefined)
      {
        ruleForm.dv_doc_pic = rulelist.value[0].response.result.url;
      }else{
        ruleForm.dv_doc_pic = rulelist.value[0].url;
      }
      if (rulelist2.value[0].response != undefined)
      {
        ruleForm.dv_drive_lic = rulelist2.value[0].response.result.url;
      }else{
        ruleForm.dv_drive_lic = rulelist2.value[0].url;
      }
      ruleFormRef.value.validate((valid) => {
        if (valid) {
          //这里可以执行提交表单的操作，比如发送请求到后端
          if (ruleForm.dv_drvr_st == true) ruleForm.dv_drvr_st = "0";
          else ruleForm.dv_drvr_st = "1";
          if (ruleForm.dv_id == 0) {
            $http
              .post("http://localhost:5261/api/Drivers/AddDrivers", ruleForm)
              .then((res) => {
                if (res) {
                  ElMessage.success("添加成功！！！");
                  setTimeout(() => {
                    router.push("/Drivers");
                  }, 500);
                } else {
                  ElMessage.error("添加失败！！！");
                }
              })
              .catch((err) => console.log(err));
          } else {
            ruleForm.update_by = sessionStorage.getItem("empname");
            ruleForm.update_time = new Date()
              .toISOString()
              .slice(0, 10)
              .toString();
            $http
              .put("http://localhost:5261/api/Drivers/UpdDrivers", ruleForm)
              .then((res) => {
                ElMessage.success("修改成功！！！");
                setTimeout(() => {
                  router.push("/Drivers");
                }, 500);
              })
              .catch((err) => console.log(err));
          }
        } else {
          //验证没有通过
          ElMessage.warning("请填写完整数据！！！");
        }
      });
    }

    function show(id) {
      $http
        .get("http://localhost:5261/api/Drivers/GetDriver", {
          params: {
            id: id,
          },
        })
        .then((res) => {
          ruleForm.dv_id = res.dv_id;
          ruleForm.dv_name = res.dv_name;
          ruleForm.dv_phone = res.dv_phone;
          ruleForm.dv_identy = res.dv_identy;
          ruleForm.dv_gender = res.dv_gender;
          ruleForm.dv_dl_type = res.dv_dl_type;
          ruleForm.dv_dl_expiry = res.dv_dl_expiry;
          ruleForm.dv_carrier = res.dv_carrier;
          ruleForm.dv_address = res.dv_address;
          ruleForm.dv_emg_cont = res.dv_emg_cont;
          ruleForm.dv_emg_ph = res.dv_emg_ph;
          rulelist.value.push({ url: res.dv_doc_pic, name: "1" });
          rulelist2.value.push({ url: res.dv_drive_lic, name: "2" });
          ruleForm.dv_doc_pic = res.dv_doc_pic;
          ruleForm.dv_drive_lic = res.dv_drive_lic;
          ruleForm.dv_cmts = res.dv_cmts;
          if (res.dv_drvr_st == 0) ruleForm.dv_drvr_st = true;
          else ruleForm.dv_drvr_st = flase;
        })
        .catch((err) => console.log(err));
    }

    function showGender(value) {
      $http
        .get("http://localhost:5261/api/Sys_Dict_data/Get_Dict_Types", {
          params: {
            Dict_name: value,
          },
        })
        .then((res) => {
          if (value == "性别") options.value = res;
          if (value == "驾照类型") options2.value = res;
        })
        .catch((err) => console.log(err));
    }

    function showCarrier() {
      $http
        .get("http://localhost:5261/api/Carrier_ment/Carrier_Ments")
        .then((res) => {
          options3.value = res;
        })
        .catch((err) => console.log(err));
    }

    function cancel() {
      router.push("/Drivers");
    }

    onMounted(() => {
      openFullScreen1();
      showGender("性别");
      showGender("驾照类型");
      showCarrier();
      name.value = route.query.name;
      var id = route.query.id;
      console.log(ruleForm.dv_drvr_st);
      if (id != 0) {
        show(id);
      }
    });

    const openFullScreen1 = () => {
      loading.value = true;
      setTimeout(() => {
        loading.value = false;
      }, 500);
    };

    return {
      loading,
      name,
      route,
      options,
      options2,
      options3,
      dialogImageUrl,
      dialogVisible,
      ruleForm,
      rules,
      ruleFormRef,
      rulelist,
      rulelist2,
      disabled,
      router,
      upload2,
      openFullScreen1,
      showCarrier,
      handleRemove,
      handlePictureCardPreview,
      handleDownload,
      handleExceed,
      handleUploadSuccess,
      handleUploadError,
      onSubmit,
      show,
      handleExceed2,
      cancel,
      upload,
    };
  },
};
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
}
.el-row:last-child {
  margin-bottom: 0;
}
.el-col {
  border-radius: 4px;
}
.grid-content {
  border-radius: 4px;
  min-height: 50px;
  background-color: #006eff;
}

.el-radio-group {
  margin-right: 12px;
}
.t_div {
  margin-bottom: 20px;
  text-align: left;
  font-size: 14px;
  color: #b3b4b6;
}
a {
  text-decoration: none;
}
.f_div {
  padding: 0px 50px;
}
.h_div {
  border-bottom: 1px solid #f2f2f2;
  height: 39px;
}
.h_in_vid {
  width: 100px;
  height: 20px;
  margin-top: 20px;
  border-left: 5px solid #006eff;
}
.header {
  background-color: #ffffff;
  border-radius: 10px 10px 0px 0px;
}
.main {
  background-color: #ffffff;
  border-radius: 0px 0px 10px 10px;
  height: 820px;
}
.form_content {
  margin-left: 50px;
}
</style>